#!/bin/bash
#
### BEGIN INIT INFO
# Provides: minig-backend
# Required-Start: $syslog $network
# Required-Stop: $syslog $network
# Default-Start: 2 3 4 5
# Default-Stop: S 0 1 6
# Short-Description: MiniG Backend.
# Description: init system for minig-backend. Starts the equinox server
#              process with minig plugins deployed.
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
export JAVA_HOME=/usr/lib/jvm/java-6-sun
test -d /usr/lib/jvm/java-1.6.0-openjdk && {
  JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk
}
test -d /usr/lib/jvm/java-openjdk && {
  JAVA_HOME=/usr/lib/jvm/java-openjdk
}


test -f $JAVA_HOME/bin/java || {
    echo "JDK not found in JAVA_HOME: $JAVA_HOME"
    exit 1
}

if [ -r /etc/default/locale ]; then
  . /etc/default/locale
  export LANG
fi
if [ -r /etc/sysconfig/i18n ]; then
  . /etc/sysconfig/i18n
  export LANG
fi



minigb_pid=/var/run/minig-backend.pid
minigb_home=/usr/share/minig-backend
minigb_logs=/var/log/minig/minig-backend.log
jps=$JAVA_HOME/bin/jps

minig_running() {
    test -f ${minigb_pid} || return 1
    supposed_pid=`cat ${minigb_pid}`
    ret=`$jps |grep -q ${supposed_pid}`
    return $ret
}

start_minig() {
    minig_running && {
	echo "MiniG Backend already running."
        ret=0
	return $ret
    }
    cd /var/log/minig
    ${minigb_home}/webmail-backend >> ${minigb_logs} 2>&1 &
    new_pid=$!
    echo $new_pid > $minigb_pid 
    echo "MiniG Backend started: `cat ${minigb_pid}`"
    ret=0
}

stop_minig() {
    minig_running || {
	echo "MiniG Backend not running."
        ret=0
	return $ret
    }
    if [ -f /sbin/start-stop-daemon ]; then
      start-stop-daemon --stop --quiet --oknodo --pidfile ${minigb_pid}
    else
      kill `cat ${minigb_pid}`
    fi
    echo -n "Waiting for Minig Backend shutdown."
    while minig_running; do
    echo -n "."
    sleep 0.5
    done
    rm -f ${minigb_pid}
    echo ""
    ret=0
}

status_minig() {
    minig_running && {
        echo "MiniG Backend is running."
        ret=0
        return $ret
    }
    echo "MiniG Backend not running"
    ret=3
}

case "$1" in
    start)
        start_minig
        ;;
    
    stop)
        stop_minig
        ;;
    status)
        status_minig
        ;;
    restart)
        stop_minig
        start_minig
        ;;
esac

exit $ret
